package com.lhn.interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author lhn
 * @date 2022/09/03 21:38
 * @since 1.0.0
 **/
public class InterruptDemo {

    static volatile boolean isStopped = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    static final Object lock = new Object();

    public static void main(String[] args) {
        case3();
    }

    private static void case3() {
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {

                        System.out.println("程序终止！");
                        break;
                    }
                }
                System.out.println("hello world!");
            }
        }, "t1");
        t1.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(t1::interrupt, "t2").start();
    }

    private static void case2() {
        new Thread(() -> {
            while (true) {
                if (atomicBoolean.get()) {
                    System.out.println("程序终止！");
                    break;
                }
                System.out.println("hello world!");
            }
        }, "t1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            atomicBoolean.set(true);
        }, "t2").start();
    }

    private static void case1() {
        new Thread(() -> {
            while (true) {
                if (isStopped) {
                    System.out.println("程序终止！");
                    break;
                }
                System.out.println("hello world!");
            }
        }, "t1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            isStopped = true;
        }, "t2").start();
    }

}